<template>
	<view class="content">
		<text class="tv-title">{{orderVO.goodsName}}</text>
		<view class="view-money">
			<text>¥</text>
			<text class="tv-amount">{{showMoney(orderVO.amount)}}</text>
		</view>
		<view class="view-payee">
			<text class="tv-payee-title">收款方</text>
			<text class="tv-payee-name">{{orderVO.payeeName||orderVO.payeeId}}</text>
		</view>
		<view class="btn-submit" :style="[btnStyle]" @click="submit()">确认支付</view>
		<pai-modal :show="isPaySuccess" title="支付成功" content='由于安全限制，需要手动点击返回应用!' :maskClose="false" :showCancel="false"
			confirmText="返回APP" @confirm="confirmBtn" @cancel="isPaySuccess=false">
		</pai-modal>
		<pai-modal :show="isCancel" title="温馨提示" content='订单超时，请关闭后重试!' :showCancel="false" confirmText="返回APP"
			@confirm="confirmBtn" @cancel="isCancel=false">
		</pai-modal>
	</view>
</template>

<script>
	import {
		getUserOpenId,
		orderMiniapp,
		getOderCache,
		rePayOrder,
		getOrderStatus
	} from '../../api/order.js'

	import {
		checkPayInfo,
		getCacheOrder
	} from '../../model/payModel.js'

	import paiModal from '../pai-modal.vue'

	import * as consts from '../../consts.js'

	export default {
		props: {
			btnBg: {
				type: String,
				default: ""
			}
		},
		components: {
			paiModal
		},
		data() {
			return {
				orderVO: {
					amount: "",
					goodsNo: "",
					payeeId: "",
					payeeName: ""
				},
				btnStyle: {
					backgroundColor: ""
				},
				isPayLoading: false, //付费中
				openId: "", //openId存在，不会重复获取
				request2: "",
				publicKey: "",
				isPaySuccess: false,
				payInfo: {},
				isCancel: false
			}
		},
		mounted() {
			this.btnStyle = {
				backgroundColor: this.btnBg || "#2D63CA"
			}
		},
		methods: {
			initData(key) {
				if (!key) {
					this.toast("缓存密钥不能为空")
				}
				this.publicKey = key
				uni.showLoading({
					title: '加载中...'
				})
				getCacheOrder(key, (orderInfo) => {
					uni.hideLoading()
					if (!orderInfo?.orderVO) {
						this.toast("订单异常")
						return
					}
					this.orderVO = orderInfo.orderVO || {}
					if (!this.orderVO.bizOrderNo) {
						return
					}
					this.checkExistPayInfo((repay) => {
						this.optionPayment(repay)
					})
				})
			},
			toast(text) {
				uni.showToast({
					title: text,
					duration: 1200
				})
			},
			checkExistPayInfo(callback) {
				if (!this.orderVO?.bizOrderNo) {
					callback(4)
					return
				}
				getOrderStatus(this.orderVO?.bizOrderNo).then(res => {
					let data = res.data?.data || {}
					if (res.data?.code == 200 && data?.tradeStatus == 0) {
						this.checkRepayOrder(callback)
					} else if (res.data?.code == 999) { //操作频繁，稍后操作
						callback(3)
					} else if (res.data?.code == 404) { //订单不存在，开始下单
						callback(2)
					} else if (data?.tradeStatus != 0) { //订单已操作
						callback(5)
					}
				}).catch(err => {
					callback(4)
				})
			},
			checkRepayOrder(callback) {
				rePayOrder(this.orderVO?.bizOrderNo).then(res => {
					let data = res.data?.data || {}
					if (res.data?.code == 200 && data?.payInfo) {
						this.payInfo = data?.payInfo
						callback(1)
					} else {
						callback(4)
					}
				}).catch(err => {
					callback(4)
				})
			},
			showMoney(money) {
				if (!money || money == 0) {
					return "0.00"
				}
				var value = Math.round(parseFloat(money)) / 100
				var xsd = value.toString().split(".")
				if (xsd.length == 1) {
					return value.toString() + ".00"
				} else if (xsd.length > 1) {
					if (xsd[1].length < 2) {
						return value.toString() + "0";
					} else {
						return value
					}
				} else {
					return value
				}
			},
			submit() {
				if (this.isPayLoading) {
					return
				}
				this.isPayLoading = true
				setTimeout(() => {
					this.isPayLoading = false
				}, 3000)

				if (!this.orderVO?.bizOrderNo) {
					this.toast("订单异常")
					return
				}

				if (this.isPaySuccess) {
					uni.showToast({
						title: "已支付，请点击退出",
						duration: 2000
					})
					return
				}
				this.checkExistPayInfo((repay) => {
					this.optionPayment(repay)
				})
			},
			optionPayment(repay) {
				switch (repay) {
					case 1:
						this.confirmRepay()
						break;
					case 2:
						setTimeout(() => {
							this.payment()
						}, 400)
						break;
					case 3:
						this.toast("操作频繁")
						break;
					case 5:
						console.log("-->>>sss:", this.isCancel)
						this.isCancel = true
						break;
					default:
						this.toast("订单异常")
						break;
				}
			},
			payment() {
				// #ifdef MP-ALIPAY
				this.aliPayment()
				// #endif
				// #ifdef MP-WEIXIN
				this.wxPayment()
				// #endif
			},
			aliPayment() {
				my.getAuthCode({
					scopes: 'auth_base',
					success: (res) => {
						var alicode = res.authCode;
						let request = {
							appId: consts.ALI_APPID,
							code: alicode,
							payMethod: "08" //支付宝小程序
						}
						this.getUserOpenId(request)
					}
				});
			},
			wxPayment() {
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: (res) => {
						var wxcode = res.code;
						let request = {
							appId: consts.WX_APPID,
							code: wxcode,
							payMethod: "04" //微信小程序
						}
						this.getUserOpenId(request)
					},
					fail: (error) => {
						uni.showToast({
							title: error
						})
					}
				})
			},
			getUserOpenId(request) {
				if (this.openId) {
					this.assemblePayParams(request)
					return
				}
				getUserOpenId(request).then(res => {
					if (res.data.code != 200 || !res.data.data) {
						return
					}
					this.openId = res.data.data
					this.assemblePayParams(request)
				}).catch(err => {
					this.payResultCallback("失败")
				})
			},
			assemblePayParams(request) {
				let info = {
					key: this.publicKey,
					openId: this.openId,
					orderType: "1",
					...request
				}
				this.startPayment(info)
			},
			startPayment(info) {
				console.log("-->info", info)
				uni.showLoading({
					title: '加载中'
				});
				orderMiniapp(info).then(res => {
					uni.hideLoading();
					console.log("-->orderMiniapp", res)
					if (res.data.code != 200 || !res.data.data) {
						this.toast(res.data?.msg || "订单获取失败")
						return
					}
					let obj = res.data.data.payInfo
					if (!obj) {
						this.toast("订单获取失败")
					}
					let payInfo = (typeof obj === 'string') ? JSON.parse(obj) : obj
					this.$emit("payInfo", payInfo)
				}).catch(err => {
					uni.hideLoading();
					this.payResultCallback(JSON.stringify(error))
				})
			},
			paySuccessCallback(success) {
				this.isPaySuccess = success
			},
			payResultCallback(text) {
				var title = '支付成功';
				var icon_name = "success";
				if (text) {
					icon_name = "error";
					title = text;
				}
				uni.showToast({
					title: title,
					icon: icon_name,
					duration: 2000
				})
			},
			confirmRepay() {
				let payInfo = (typeof this.payInfo === 'string') ? JSON.parse(this.payInfo) : this.payInfo
				this.$emit("payInfo", payInfo)
			},
			confirmBtn() {
				uni.exitMiniProgram({
					success: function() {
						console.log('退出小程序成功');
					},
					fail: function(err) {
						console.log('退出小程序失败', err);
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	// page {
	// 	min-height: 100%;
	// 	width: 100%;
	// 	background-color: #F7F7F7;
	// }

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		// width: 100%;
		flex: 1;

		.tv-title {
			font-size: 28rpx;
			color: #1D1D1D;
			margin-top: 48rpx;
		}

		.view-money {
			font-weight: 600;
			color: #1B1B1B;

			.tv-amount {
				margin-left: 8rpx;
				font-size: 64rpx;
			}
		}

		.view-payee {
			align-self: stretch;
			display: flex;
			margin-top: 32rpx;
			justify-content: space-between;
			line-height: 92rpx;
			height: 92rpx;
			border-bottom: 1rpx solid #E6E6E6;
			border-top: 1rpx solid #E6E6E6;
			background-color: #ffffff;

			.tv-payee-title {
				font-size: 28rpx;
				color: #7E7E7E;
				margin-left: 32rpx;
			}

			.tv-payee-name {
				font-size: 28rpx;
				color: #1D1D1D;
				margin-right: 32rpx;
			}
		}
	}

	.btn-submit {
		height: 80rpx;
		font-size: 32rpx;
		align-self: stretch;
		margin: 68rpx 32rpx;
		color: #ffffff;
		border-radius: 12rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.view-btn {
		margin: 24rpx;
	}

	.btn-submit:active {
		opacity: 0.6;
	}

	.text-tv {
		padding: 32rpx;
		width: 80%;
		background-color: #fafafa;
	}
</style>